package cn.bytest.netty.inovker;

import cn.bytets.rpc.api.exchange.ExchangeClient;
import cn.bytets.rpc.api.invoke.AbstractInvoker;
import cn.bytets.rpc.api.invoke.Invocation;
import cn.bytets.rpc.api.invoke.Invoker;
import cn.bytets.rpc.api.message.AsyncRpcResult;
import cn.bytets.rpc.api.message.Result;
import cn.bytets.rpc.common.URL;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;

public class SpeedRpcInvoker extends AbstractInvoker {

    private Class<?> interfaceClass;

    private final ExchangeClient[] clients;

    private final Map<Invoker<?>,Object> invokers;

    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    public SpeedRpcInvoker(Class<?> interfaceClass, URL url,ExchangeClient[] clients,Map<Invoker<?>,Object> invokers){
        super(interfaceClass,url);
        this.interfaceClass = interfaceClass;
        this.clients = clients;
        this.invokers = invokers;
    }
    /**
     * get service interface.
     *
     * @return service interface.
     */
    @Override
    public Class getInterface() {
        return this.interfaceClass;
    }

    @Override
    public Result doInvoker(Invocation invocation) {
        ExchangeClient currentClient;
        if (clients.length == 1) {
            currentClient = clients[0];
        } else {
            currentClient = clients[atomicInteger.incrementAndGet() % clients.length];
        }
        AsyncRpcResult result = new AsyncRpcResult(invocation);
        CompletableFuture<Object> request = currentClient.request(invocation, getUrl());
        result.subscribeTo(request);
        return result;
    }
}
